package consultoria.commands;

import handlers.DeleteSelectionHandler;

import java.util.Collections;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.expressions.IEvaluationContext;
import org.eclipse.jface.action.ContributionItem;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MenuAdapter;
import org.eclipse.swt.events.MenuEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.IHandlerService;

public class DeleteContributionItem extends ContributionItem {

	public DeleteContributionItem() {
		// TODO Auto-generated constructor stub
	}

	public DeleteContributionItem(String id) {
		super(id);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void fill(Menu menu, int index) {
		IStructuredSelection struSel = (IStructuredSelection) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart().
				getSite().getSelectionProvider().getSelection();

		String labelObjs = "";
		for (Object objLabel : struSel.toArray()) {
			labelObjs += objLabel.toString()+",";
		}

		final MenuItem menuItem = new MenuItem(menu, SWT.PUSH, index);
		menuItem.setText("Delete "+labelObjs);
		menuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				run();
			}
		});
		menu.addMenuListener(new MenuAdapter() {
			public void menuShown(MenuEvent e) {
				updateState(menuItem);
			}
		});


	}

	protected void updateState(MenuItem menuItem) {
		// TODO Auto-generated method stub

	}

	protected void run() {
		final IHandlerService handlerService = (IHandlerService)
				PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart().getSite().getService(IHandlerService.class);
		IEvaluationContext evaluationContext = handlerService.createContextSnapshot(true);
		ExecutionEvent event =
				new ExecutionEvent(null, Collections.EMPTY_MAP, null,
						evaluationContext);
		try {
			new DeleteSelectionHandler().execute(event);
		}
		catch (ExecutionException e) {
			e.printStackTrace();
		}

	}

	@Override
	public boolean isDynamic() {
		return true;
	}



}
